import axios from 'axios'

/**
 * 日期格式化
 * @param time
 * @param pattern
 * @returns {string|null}
 * @author 赵京涛
 */
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.\d{3}/gm), '')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(/{(y+|m+|d+|h+|i+|s+|a+)(-)}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}

/**
 * 表单重置
 * @param vm vue组件实例
 * @param refName ref
 * @author 赵京涛
 */
export const resetForm = (vm, refName) => {
  if (vm.$refs[refName]) {
    vm.$refs[refName].resetFields()
  }
}

/**
 * 添加日期范围
 * @param params
 * @param dateRange
 * @param propName
 * @returns {*}
 * @author 赵京涛
 */
export function addDateRange(params, dateRange, propName) {
  const search = params
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {}
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0]
    search.params['endTime'] = dateRange[1]
  } else {
    search.params['begin' + propName] = dateRange[0]
    search.params['end' + propName] = dateRange[1]
  }
  return search
}

/**
 * 回显数据字典
 * @param datas
 * @param value
 * @author 赵京涛
 * @returns {string}
 */
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return ''
  }
  const actions = []
  Object.keys(datas).some((key) => {
    if (datas[key].value === ('' + value)) {
      actions.push(datas[key].label)
      return true
    }
  })
  if (actions.length === 0) {
    actions.push(value)
  }
  return actions.join('')
}

/**
 * 回显数据字典（字符串、数组）
 * @param datas
 * @param value
 * @author 赵京涛
 * @param separator
 * @returns {string}
 */
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return ''
  }
  if (Array.isArray(value)) {
    value = value.join(',')
  }
  const actions = []
  const currentSeparator = undefined === separator ? ',' : separator
  const temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some((val) => {
    let match = false
    Object.keys(datas).some((key) => {
      if (datas[key].value === ('' + temp[val])) {
        actions.push(datas[key].label + currentSeparator)
        match = true
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator)
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

/**
 * 字符串格式化(%s )
 * @param str
 * @author 赵京涛
 * @returns {*|string}
 */
export function sprintf(str) {
  const args = arguments
  let flag = true
  let i = 1
  str = str.replace(/%s/g, function () {
    const arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

/**
 * 转换字符串，undefined,null等转化为""
 * @param str
 * @author 赵京涛
 * @returns {*|string}
 */
export function parseStrEmpty(str) {
  if (!str || str === 'undefined' || str === 'null') {
    return ''
  }
  return str
}

/**
 * 数据合并
 * @param source
 * @param target
 * @author 赵京涛
 * @returns {*}
 */
export function mergeRecursive(source, target) {
  for (const p in target) {
    try {
      if (target[p].constructor === Object) {
        source[p] = mergeRecursive(source[p], target[p])
      } else {
        source[p] = target[p]
      }
    } catch (e) {
      source[p] = target[p]
    }
  }
  return source
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @author zjt
 */
export function handleTree(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

/**
 * 参数处理
 * @author 赵京涛
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof (value[key]) !== 'undefined') {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}

/**
 * 验证是否为blob格式
 * @param data
 * @author 赵京涛
 * @returns {boolean}
 */
export function blobValidate(data) {
  return data.type !== 'application/json'
}

/**
 * 动态生成弹窗内表单信息
 * @param obj
 * @author 赵京涛
 * @returns {*[]}
 */
export const convertObjectToFormFields = (obj) => {
  const formFields = []
  for (const key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      formFields.push({
        key: key,
        label: obj[key],
        type: 'text',
        value: ''
      })
    }
  }
  return formFields
}

/**
 * 转换表单VO对象实体 有type
 * @param obj
 * @param typeArr
 * @author 赵京涛
 * @returns {string}
 */
export const convertObjectToNewStructure = (obj, typeArr = []) => {
  const result = []
  for (const key in obj) {
    const _resultType = typeArr?.find(item => item.fieldCode === key)
    _resultType ? result.push({
      fieldCode: key,
      type: _resultType.type || '',
      value: obj[key]
    }) : result.push({
      fieldCode: key,
      type: '',
      value: obj[key]
    })
  }
  if (result && Array.isArray(result) && result.length > 0) {
    return JSON.stringify(result.filter(p => p.type !== ''))
  }
}

/**
 * 转换表单VO对象实体 无type
 * @param obj
 * @returns {string}
 * @author 赵京涛
 */
export const convertObjectToNewStructureNoType = (obj) => {
  const result = []
  for (const key in obj) {
    result.push({
      fieldCode: key,
      type: '',
      value: obj[key]
    })
  }
  return JSON.stringify(result)
}

/**
 * 转换表单VO对象实体 其他报送上传type
 * @param obj
 * @param fileldList
 * @returns {string}
 * @author 赵京涛
 */
export const convertObjectToNewStructureFieldCode = (obj, fileldList) => {
  const result = []
  for (const key in obj) {
    const _resultType = fileldList?.find(item => item.fieldCode === key)
    _resultType ? result.push({
      fieldCode: key,
      type: _resultType.type || '',
      value: obj[key]
    }) : result.push({
      fieldCode: key,
      type: '',
      value: obj[key]
    })
  }
  return JSON.stringify(result)
}

/**
 * 转换表单VO对象实体 text
 * @param obj
 * @returns {string}
 * @author 赵京涛
 */
export const convertObjectTextNewStructureNoType = (obj) => {
  const result = []
  for (const key in obj) {
    result.push({
      fieldCode: key,
      type: 'text',
      value: obj[key]
    })
  }
  return JSON.stringify(result)
}

/**
 * 检测对象在数组中出现的索引
 * @param obj
 * @param arr
 * @returns {number}
 * @author 赵京涛
 */
export const findIndexInArray = (obj, arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (JSON.stringify(arr[i]) === JSON.stringify(obj)) {
      return i
    }
  }
  return -1
}

/**
 * 获取一级菜单名称
 * @param arr 原始数据
 * @param oneIndex 第一级数组索引
 * @param twoIndex 第二级数组索引
 * @param targetDataId 目标一级菜单ID
 * @author 赵京涛
 * @returns {*}
 */
export const formatterDataIdName = (arr, oneIndex, twoIndex, targetDataId) => {
  const newArr = JSON.parse(JSON.stringify(arr))
  if (newArr && typeof newArr === 'object' && newArr.length > 0) {
    return newArr[oneIndex]?.list?.[twoIndex]?.list?.find(s => s.name === targetDataId)['dataName']
  }
}

/**
 * 获取二级菜单名称
 * @param arr 原始数据
 * @param oneIndex 第一级数组索引
 * @param twoIndex 第二级数组索引
 * @param targetDataId 目标一级菜单ID DataId
 * @param targetReportId 目标二级菜单ID reportId
 * @author 赵京涛
 * @returns {*}
 */
export const formatterReportIdName = (arr, oneIndex, twoIndex, targetDataId, targetReportId) => {
  const newArr = JSON.parse(JSON.stringify(arr))
  if (newArr && typeof newArr === 'object' && newArr.length > 0) {
    const targetData = newArr[oneIndex]?.list?.[twoIndex]?.list?.find(s => s.name === targetDataId)
    if (targetData) {
      return targetData?.list?.find(u => u.reportId === targetReportId)['dataName']
    }
  }
}

/**
 *  针对于 [‘’，‘’，‘’，‘’]数据结构 和 [{key:,value:}]数据结构
 * @param self 组件实例
 * @param apiData 接口数据
 * @param compData 组件data
 * @param fieldName options列表名称
 * @author 赵京涛
 * @returns {*}
 */
export const getIsPortIsOneDisposeDataStructure = (self, apiData, compData, fieldName) => {
  if (apiData && Array.isArray(apiData) && apiData.every(g => typeof g === 'string')) {
    if (apiData && apiData.length > 0) {
      const optionList = []
      apiData.forEach(r => optionList.push({ label: r, value: r }))
      const _info = compData.find(g => g.fieldName === fieldName)
      _info.options = optionList
      const _idx = findIndexInArray(_info, compData)
      self.$set(compData, _idx, _info)
      return compData
    } else {
      const _info = compData.find(g => g.fieldName === fieldName)
      _info.options = []
      const _idx = findIndexInArray(_info, compData)
      self.$set(compData, _idx, _info)
      return compData
    }
  } else {
    if (apiData && apiData.length > 0) {
      const optionList = []
      apiData?.forEach(r => optionList.push({ label: r.value, value: r.key }))
      const _info = compData.find(g => g.fieldName === fieldName)
      _info.options = optionList
      const _idx = findIndexInArray(_info, compData)
      self.$set(compData, _idx, _info)
      return compData
    }
  }
}

/**
 * 单次评价点位数据结构转换成树状数据结构
 * @param data 原始数据结构
 * @author 赵京涛
 */
export const convertToTreeStructureHandler = (data) => {
  const result = []
  data.forEach((item, index) => {
    const parent = {
      value: index + 1,
      label: item.name,
      children: []
    }
    if (item.list && Array.isArray(item.list) && item.list.length > 0) {
      item.list.forEach((subItem) => {
        parent.children.push({
          value: subItem['uniqueCode'],
          label: `${subItem.dwmc}`
        })
      })
    }
    result.push(parent)
  })
  return result
}

/**
 * 查找索引
 * @param fieldCode
 * @param array
 * @returns {number}
 * @author 赵京涛
 */
export const findIndexInArraysCode = (fieldCode, array) => {
  for (let i = 0; i < array.length; i++) {
    if (array[i].fieldCode === fieldCode) {
      return i
    }
  }
  return -1
}

/**
 * 移动节点（上下移动，置顶置底）
 * @param self
 * @param type
 * @param checkLabel
 * @param dataList
 * @author 赵京涛
 */
export const moveNodeRenewalDOMHandler = (self, type, checkLabel, dataList) => {
  if (type === 'prev') {
    return {
      arrayIndex: 0,
      arrayIndexNow: checkLabel - 1,
      msg: '已经是第一位了！'
    }
  } else if (type === 'next') {
    return {
      arrayIndex: dataList.length - 1,
      arrayIndexNow: checkLabel + 1,
      msg: '已经是最后一位了！'
    }
  } else if (type === 'top') {
    return {
      arrayIndex: 0,
      arrayIndexNow: 0,
      msg: '已经是第一位了！'
    }
  } else if (type === 'bottom') {
    return {
      arrayIndex: dataList.length - 1,
      arrayIndexNow: dataList.length - 1,
      msg: '已经是最后一位了！'
    }
  }
}

/**
 * 把columnName名一样的那一项数据最后统一放在list里面
 * 'category': '最大值点位','key': 'sw_max_dw',使用list数组中的第一项
 * @param arr
 * @author 赵京涛
 */
export const columnNameTransformArrayAccording = (arr) => {
  let hasSameColumnName = false
  const map = new Map()
  const result = arr.reduce((acc, item) => {
    if (item.category !== '') {
      if (!map.has(item.columnName)) {
        map.set(item.columnName, {
          columnName: item.columnName,
          category: item.category,
          rowspan: 2,
          colspan: 1,
          label: '',
          key: item.key,
          list: [item]
        })
      } else {
        map.get(item.columnName).list.push(item)
        hasSameColumnName = true
      }
      return acc
    } else {
      acc.push(item)
      return acc
    }
  }, [])
  if (!hasSameColumnName) {
    return arr
  }
  map.forEach(value => {
    result.push(value)
  })
  return result
}
/**
 * 三级表头处理 => headerThirdRow newMap 和 newSet
 * @param originalData 原始数据
 * @author 赵京涛
 */
export const threeColumnNameTransformDataStructure = (originalData) => {
  const transformedDataMap = originalData.reduce((acc, { columnName, category, ...rest }) => {
    if (columnName && category) {
      if (!acc.has(columnName)) {
        acc.set(columnName, { columnName, list: [] })
      }
      const currentItem = acc.get(columnName)
      if (!currentItem.list.some(item => item.category === category)) {
        currentItem.list.push({ category, list: [] })
      }
      const categoryItem = currentItem.list.find(item => item.category === category)
      categoryItem.list.push({ columnName, category, ...rest })
    } else {
      acc.set(columnName, { columnName, category, ...rest })
    }
    return acc
  }, new Map())
  return Array.from(transformedDataMap.values())
}

/**
 * 转换顺序
 * @author 赵京涛
 * @param original
 * @param transformed
 * @returns {*[]}
 */
export const transformOrder = (original, transformed) => {
  return original.map((item) => {
    const found = transformed.find((t) => t.key === item.key)
    return found || null
  }).filter((item) => item !== null)
}

/**
 * 对比原始数据结构和目标数据结构中的值，并在原始数据结构中找到匹配的项时添加 disabled: true 属性
 * @param originalArr 原始数据
 * @param targetArr 目标数组
 * @returns {*}
 * @author 赵京涛
 */
export const compareAndDisable = (originalArr, targetArr) => {
  return originalArr.map((originalItem) => ({
    ...originalItem,
    disabled: targetArr.some((targetItem) => targetItem.value === originalItem.value)
  }))
}

/**
 * POST导出word文件
 * @param url
 * @param param
 * @param fileName
 */
export const exportWordFileHandler = (url, param, fileName) => {
  let shuju = ''
  if (param) {
    const data = JSON.parse(JSON.stringify(param))
    for (const key in data) {
      if (typeof data[key] === 'object') {
        delete data[key]
      } else {
        if (shuju === '') {
          shuju += key + '=' + data[key]
        } else {
          shuju += '&' + key + '=' + data[key]
        }
      }
    }
    param = data
    console.log('导出传递的参数：', param)
  }
  axios
    .post(`${process.env.VUE_APP_BASE_API}` + url, shuju, {
      responseType: 'arraybuffer'
    })
    .then((response) => {
      // 创建一个blob对象
      const blob = new Blob([response.data], { type: 'application/msword' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      // 配置下载的文件名
      link.download = `${fileName}.docx`
      link.click()
    })
}

/**
 * 日月选项切换之后获取到 日期选择的年份赋值给年份选择器 将需要传递的参数return
 * @param initParameterParams 初始传递参数JSON
 * @param dayTimeList 日期选择绑定值
 * @param startYear 开始年份
 * @param endYear 结束年份
 * @param sunMoonTabs 日|月绑定值
 * @param yearList 年数据集合
 * @author 赵京涛
 */
export const useDayMoonSwitchingTimeParams = (initParameterParams, dayTimeList, startYear, endYear, sunMoonTabs, yearList) => {
  const parseData = JSON.parse(initParameterParams)
  const updatedData = parseData.map(items => {
    if (sunMoonTabs === 'day') {
      if (items.fieldCode === 'jcrq-start') {
        return { ...items, value: dayTimeList[0] }
      } else if (items.fieldCode === 'jcrq-end') {
        return { ...items, value: dayTimeList[1] }
      } else if (items.fieldCode === 'year_list') {
        return { ...items, value: yearList && Array.isArray(yearList) ? yearList.join(',') : '' }
      }
    } else if (sunMoonTabs === 'moon') {
      if (items.fieldCode === 'jcrq-start') {
        return { ...items, value: startYear + '-06-01' }
      } else if (items.fieldCode === 'jcrq-end') {
        return { ...items, value: endYear + '-08-31' }
      }
    }
    return items
  })
  return JSON.stringify(updatedData)
}

/**
 * 根据图例长度来设置图表左右偏移距离
 * @param dataLength 图例长度
 */
export const useLeftRightPositionOffset = (dataLength) => {
  let gridLeft
  let gridRight
  switch (dataLength) {
    case 1:
    case 2:
      gridLeft = '10%'
      gridRight = '10%'
      break
    case 3:
    case 4:
      gridLeft = '13%'
      gridRight = '13%'
      break
    case 5:
    case 6:
      gridLeft = '16%'
      gridRight = '16%'
      break
    case 7:
    case 8:
      gridLeft = '19%'
      gridRight = '19%'
      break
    case 9:
    case 10:
      gridLeft = '22%'
      gridRight = '22%'
      break
    case 11:
    case 12:
      gridLeft = '25%'
      gridRight = '25%'
      break
    case 13:
    case 14:
      gridLeft = '28%'
      gridRight = '28%'
      break
    default:
      gridLeft = '30%'
      gridRight = '28%'
      break
  }
  return { gridLeft, gridRight }
}

/**
 * 根据图例长度来设置图表纵坐标偏移量和内边距
 * @param dataLength 图例长度
 */
export const useLocationTypePaddingHooks = (dataLength) => {
  let locationType
  let padding
  switch (dataLength) {
    case 1:
    case 2:
      locationType = 120
      padding = 68
      break
    case 3:
    case 4:
      locationType = 100
      padding = 33
      break
    case 5:
    case 6:
      locationType = 95
      padding = 30
      break
    case 7:
    case 8:
      locationType = 90
      padding = 27
      break
    case 9:
    case 10:
      locationType = 85
      padding = 24
      break
    case 11:
    case 12:
      locationType = 75
      padding = 21
      break
    case 13:
    case 14:
      locationType = 65
      padding = 21
      break
    default:
      locationType = 63
      padding = 20
      break
  }
  return { locationType, padding }
}



/**
 * 通过输入的ID值返回当前一级父级的code集合
 * @param district
 * @param targetId
 * @returns {*[]}
 */
export const useFindCodesListArr = (district, targetId) => {
  const parentIds = []
  let currentItem = null
  // 辅助函数，用于递归查找父级并收集 id
  function traverse(items) {
    for (const item of items) {
      if (item.id === targetId) {
        currentItem = item
        break
      } else if (item.subList) {
        const found = traverse(item.subList)
        if (found) {
          return true // 表示在子列表中找到了目标项
        }
      }
    }
    return false // 表示在当前列表中没有找到目标项
  }
  // 开始遍历
  traverse(district)
  // 如果找到了目标项，则收集其父级 id
  if (currentItem) {
    let parent = currentItem
    do {
      parentIds.unshift(parent.id) // 将父级 id 添加到数组开头
      // 寻找上一级父项
      parent = district.find(item => item.subList && item.subList.includes(parent))
    } while (parent && parent.id !== parent.parentCode) // 当到达顶级父项时停止，假设顶级父项的 id 和 parentCode 相同
  }
  return parentIds
}


/**
 * 路由元信息添加列表接口地址
 * @param {*} routes 
 */
export const useUpdateMetaWithApiUrl = (routes) => {
  routes.forEach(route => {
    if (route.meta) {
      // 直接在meta中添加apiUrl，值来自同级的apiUrl  
      route.meta.apiUrl = route.apiUrl;
    }
    // 如果存在子路由，则递归处理  
    if (route.children) {
      useUpdateMetaWithApiUrl(route.children);
    }
  });
}  
